package org.zy.server;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import io.netty.channel.Channel;
import io.netty.util.AttributeKey;
import io.netty.util.internal.StringUtil;

public class ChannelManager {
    /**
     * 客户端服务channel
     */
    public static Channel CLIENT_MAIN_CHANNEL = null;

    /**
     * 绑定channel_id
     */
    public static final AttributeKey<String> VISITOR_ID = AttributeKey.newInstance("vid");

    /**
     * 客户端Channel
     */
    public static Map<String, Channel> CLIENT_CHANNEL_MAP = new ConcurrentHashMap<>();

    /**
     * 访客Channel
     */
    public static Map<String, Channel> VISITOR_CHANNEL_MAP = new ConcurrentHashMap<>();


    /**
     * 删除连接
     *
     * @param visitorId 访客ID
     */
    public static void removeVisitor(String visitorId) {
        if (StringUtil.isNullOrEmpty(visitorId)) {
            return;
        }
        Channel clientChannel = CLIENT_CHANNEL_MAP.get(visitorId);
        if (null != clientChannel) {
            clientChannel.attr(VISITOR_ID).set(null);
            CLIENT_CHANNEL_MAP.remove(visitorId);
        }
        Channel visitorChannel = VISITOR_CHANNEL_MAP.get(visitorId);
        if (null != visitorChannel) {
            visitorChannel.attr(VISITOR_ID).set(null);
            VISITOR_CHANNEL_MAP.remove(visitorId);
        }
    }

    /**
     * 清除关闭连接
     *
     * @param visitorId 访客ID
     */
    public static void removeVisitorAndClose(String visitorId) {
        if (StringUtil.isNullOrEmpty(visitorId)) {
            return;
        }
        Channel clientChannel = CLIENT_CHANNEL_MAP.get(visitorId);
        if (null != clientChannel) {
            clientChannel.attr(VISITOR_ID).set(null);
            CLIENT_CHANNEL_MAP.remove(visitorId);
            clientChannel.close();
        }
        Channel visitorChannel = VISITOR_CHANNEL_MAP.get(visitorId);
        if (null != visitorChannel) {
            visitorChannel.attr(VISITOR_ID).set(null);
            VISITOR_CHANNEL_MAP.remove(visitorId);
            visitorChannel.close();
        }
    }
}